package com.demo2do.fms.admin.service.fileupload.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.fms.admin.service.fileupload.FileUploadService;

/**
 * 
 * @author mohanlan
 *
 */
@Service("fileUploadService")
public class FileUploadServiceImpl implements FileUploadService {
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    /*
     * (non-Javadoc)
     * @see com.demo2do.fms.admin.service.fileupload.FileUploadService#saveFile(java.lang.String, java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.util.Date)
     */
    public void saveFile(String fileObject, Long objectId, String fileName, String filePath, String dateName, Date dateValue) {
        
        String sentence = "";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("filePath", filePath);
        parameters.put("id", objectId);
        
        if(StringUtils.isNoneBlank(dateName)) {
            
            if(dateValue == null) {
                throw BusinessException.newInstance("501", "保存文件失败");
            }
            
            sentence = sentence + "UPDATE " + fileObject + " SET " + fileName + " = :filePath, " + dateName + " = :date WHERE id = :id AND disabled = false";
            parameters.put("date", dateValue);
            
        } else {
            sentence = sentence + "UPDATE " + fileObject + " SET " + fileName + " = :filePath WHERE id = :id AND disabled = false";
        }
        
        int success = genericDaoSupport.executeHQL(sentence, parameters);
        if(success == 0) {
            throw BusinessException.newInstance("502", "保存文件失败"); 
        }
        
    }

}
